import { useState, useEffect } from 'react';
import { Select } from 'antd';
import TRCheckboxModal from './TRCheckboxModal';
import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { getStationLevelThree } from '@/services/user';

/**
 * 交易单元选择器组件
 * 封装为公共组件，提供给各个功能模块使用
 */
/**
 * 此函数组件主要用于从接口获取数据并处理数据
 * selectedStationIds 被选中的场站id列表
 * disabledStationIds 禁用的场站id列表
 * menuCode 菜单编码 必传
 * onChange 修改被选中的场站时的回调事件
 * className 类名
 * @returns
 */
export default function SelectStations({
  selectedStationIds = [],
  disabledStationIds = [],
  menuCode = '',
  onChange = () => {},
  className = '',
  provinceId,
}) {
  const title = '交易单元';

  const [stations, setStations] = useState([]), // 打平的交易单元列表
    [stationTree, setStationTree] = useState([]); // 树状的交易单元列表

  useEffect(() => {
    getStationData();
  }, []);

  /**
   * 获取用户有权限的所有的交易单元
   */
  const getStationData = async () => {
    const res = await getStationLevelThree(menuCode);

    if (res?.statusCode === HttpCode.SUCCESS) {
      let data = res?.data;

      // 处理数据权限
      if (!data) {
        TRMessage.error('暂无数据权限');
        return;
      }

      // 当前过滤为山西，实际处理时，会根据权限配置好，不需要过滤
      let stationTree =
        data.find((item) => {
          return item?.value === provinceId;
        })?.children || [];

      // let stationTree = data[0]?.children || [];

      // 处理数据。为了适用子组件，所有公司及场站增加key title字段，key = value title = label
      stationTree.forEach((company) => {
        company?.value && (company.key = company.value);
        company?.label && (company.title = company.label);
        (company?.children || []).forEach((station) => {
          station?.value && (station.key = station.value);
          station?.label && (station.title = station.label);
        });
      });

      let stations = [];

      stationTree.forEach((company) => {
        (company?.children || []).forEach((station) => {
          stations.push({
            ...station,
            disabled: true,
          });
        });
      });

      setStations(stations);
      setStationTree(stationTree);
    } else {
      TRMessage.error(res?.message || '获取交易单元信息失败');
    }
  };

  const setDisabledStation = () => {
    let data = JSON.parse(JSON.stringify(stationTree));
    data.forEach((company) => {
      let isUsedNum = 0;
      (company?.children || []).forEach((station) => {
        // 遍历所有交易单元，如果当前交易单元在 disabledStationIds 中存在，则禁用当前交易单元
        let isUsed = disabledStationIds.filter((item) => {
          return item + '' === station.value + '';
        })[0];
        if (isUsed) {
          station.disabled = true;
          isUsedNum++;
        }
      });
      if (isUsedNum === company?.children?.length) {
        company.disabled = true;
      }
    });
    return data;
  };

  const onHandleModal = async () => {
    if (!stations.length) {
      TRMessage.warning('您没有场站权限，请联系管理员获取相关权限');
      return;
    }

    let treeData = setDisabledStation();

    const result = await TRCheckboxModal.show({
      title,
      value: selectedStationIds,
      treeData,
      okText: '确认',
    });
    if (result?.index === 1) {
      onChange(result.checkedKeys);
    }
    TRCheckboxModal.dismiss();
  };

  return (
    <Select
      className={className}
      value={selectedStationIds}
      options={stations}
      placeholder={title}
      mode="multiple"
      maxTagCount={1}
      maxTagTextLength={selectedStationIds.length > 1 ? 2 : 8}
      open={false}
      showSearch={false}
      showArrow={true}
      onClick={onHandleModal}
    />
  );
}
